package report

import (
	"context"
	"fmt"
	"sale-admin/config"
	"sale-admin/internal/models"
	"strings"

	"192.168.1.75/go-pkg/errorx"
	"github.com/xuri/excelize/v2"
	"gorm.io/gorm"
)

type ReportService struct{}

type LogTitleInfo struct {
	Date           string `json:"date"`
	ObjectName     string `json:"object_name"`
	WebHookAddress string `json:"web_hook_address"`
	WebHookName    string `json:"web_hook_name"`
}

// 运营报告详情
func (r ReportService) LogDetail(ctx context.Context, db *gorm.DB, merchantID, ID string) (
	MySlice [][]interface{}, TitleInfo LogTitleInfo, err error) {
	if ID == "" {
		err = errorx.New("当前请求无效!", -1)
		return
	}
	// 获取运营报告记录
	var LogInfo models.MaRobotReportLog
	var LogCount int64
	db.Model(&models.MaRobotReportLog{}).
		Where("id = ?", ID).
		Take(&LogInfo).
		Count(&LogCount)
	if LogCount == 0 {
		return
	}
	// 返回标题信息
	StartTimeBytes, _ := models.DateTime(LogInfo.StartTime).MarshalDate()
	TitleInfo.Date = string(StartTimeBytes)
	if LogInfo.WebHookName == 1 {
		TitleInfo.WebHookName = "飞书"
	} else {
		TitleInfo.WebHookName = "邮件"
	}
	TitleInfo.ObjectName = LogInfo.ObjectName
	TitleInfo.WebHookAddress = LogInfo.WebHookAddress

	excelURL := strings.TrimPrefix(LogInfo.Url, config.Config.BaseUrl)
	f, err1 := excelize.OpenFile(excelURL)
	if err1 != nil {
		err = errorx.New("打开文件失败", -1)
		return
	}
	defer func() {
		if err2 := f.Close(); err2 != nil {
			err = errorx.New("关闭文件失败", -1)
		}
	}()

	rows, err := f.GetRows("Sheet1")
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, row := range rows {
		var rowData []interface{}
		for _, colCell := range row {
			rowData = append(rowData, colCell)
		}
		MySlice = append(MySlice, rowData)
	}
	return MySlice, TitleInfo, err
}
